package com.bridgetree.jubaocrm.ui.project;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.FormFile;
import com.bridgetree.jubaocrm.ui.SocketHttpRequester;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
/**
 *添加资料
 */
@SuppressLint({ "SdCardPath", "HandlerLeak" })
public class XMChildAddDataActivity extends Activity {
	private final String TAG ="XMChildAddDataActivity";
	private Projects mProjects;
	private Context mContext;
	private String filepath ="";
	private static final int IMAGE_CODE = 1001;
	private static final int TAKE_PHOTO = 1002;
	private static final int TAKE_CORP = 1003;
	private static final int FILE_TO_LARGE = 1004;
	public static final String IMAGE_UNSPECIFIED = "image/*";
	private ImageView xm_data_iv;
	private EditText xm_data_ed_name;
	private LinearLayout LinearLayoutss;
	private Button phone;
	private Button xiangce;
	private EditText xm_data_ed_con;
	private LinearLayout layoutdddd;
	private InputMethodManager mInputMethodManager ;

	private String user_ids =""; 
	private String tokens ="";
	
	//	private File file;
	private ProgressDialog progressDialog;
	private String imageDir;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xmadddata);
		mContext= this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_ids = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		tokens = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		xm_data_ed_name =(EditText)findViewById(R.id.xm_data_ed_name);
		LinearLayoutss =(LinearLayout)findViewById(R.id.LinearLayoutss);
		xm_data_ed_con =(EditText)findViewById(R.id.xm_data_ed_con);
		phone =(Button)findViewById(R.id.phone);
		xiangce =(Button)findViewById(R.id.xiangce);
		TextView xm_data_tv_title =(TextView)findViewById(R.id.xm_data_tv_title);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			xm_data_tv_title.setText("客户名片/资料");
		}
		LinearLayoutss.setVisibility(View.GONE);

		findViewById(R.id.xm_data_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//				imm.hideSoftInputFromWindow(getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
				imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); //强制隐藏键盘  
				finish();
			}
		});

		findViewById(R.id.xm_data_bt_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
				imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); //强制隐藏键盘  
				String newname = xm_data_ed_name.getText().toString().trim();
//				newname = newname.replaceAll("\\s","");
				getAddData(newname);
			}
		});


		layoutdddd=(LinearLayout)findViewById(R.id.layoutdddd);
		layoutdddd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_data_ed_con.setText(xm_data_ed_con.getText());
				xm_data_ed_con.setFocusable(true);
				xm_data_ed_con.setFocusableInTouchMode(true);
				xm_data_ed_con.setSelection(xm_data_ed_con.getText().toString().length());
				//				layoutdddd.setFocusable(true);
				//				layoutdddd.setFocusableInTouchMode(true);
				xm_data_ed_name.setFocusable(false);
				xm_data_ed_name.setFocusableInTouchMode(false);
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
				//得到InputMethodManager的实例
				if (imm.isActive()) {
					//如果开启
					//					imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
					imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, InputMethodManager.SHOW_IMPLICIT); 
					//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
				} 
			}
		});

		
		xm_data_ed_name.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_data_ed_name.setText(xm_data_ed_name.getText());
				xm_data_ed_con.setFocusable(false);
				xm_data_ed_con.setFocusableInTouchMode(false);
				//				layoutdddd.setFocusable(true);
				//				layoutdddd.setFocusableInTouchMode(true);
				xm_data_ed_name.setFocusable(true);
				xm_data_ed_name.setFocusableInTouchMode(true);
				xm_data_ed_name.requestFocus();
				xm_data_ed_name.setSelection(xm_data_ed_name.getText().toString().length());
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
				//得到InputMethodManager的实例
				if (imm.isActive()) {
					//如果开启
					//					imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
					imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, InputMethodManager.SHOW_IMPLICIT); 
					//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
				}
			}
		});
		xm_data_iv = (ImageView)findViewById(R.id.xm_data_iv);

		findViewById(R.id.xm_data_FrameLayout).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LinearLayoutss.setVisibility(View.VISIBLE);
			}
		});

		LinearLayoutss.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LinearLayoutss.setVisibility(View.GONE);
			}
		});

		phone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					LinearLayoutss.setVisibility(View.GONE);
					imageDir = "temp.jpg";
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					// 指定调用相机拍照后照片的储存路径
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), imageDir)));
					startActivityForResult(intent, TAKE_PHOTO);
				} catch (ActivityNotFoundException e) {
					e.printStackTrace();
				}
			}
		});

		xiangce.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					LinearLayoutss.setVisibility(View.GONE);
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_GET_CONTENT);
					intent.setType("image/*");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//FLAG_ACTIVITY_NEW_TASK
					startActivityForResult(intent , IMAGE_CODE);
				} catch (ActivityNotFoundException e) {
					e.printStackTrace();
				}
			}
		});


	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	File to = null;
	private void getAddData(String newName) {
		Network mNetword = new Network(mContext);
		if (filepath.equals("")) {
			openDailog("操作提示", "您没有选择上传文件！");
			return;
		} else if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
			return;
		} else if(newName.length() >10){
			openDailog("失败提示", "文件名必须小于10个字符");
			return;
		}else {
			progressDialog = ProgressDialog.show(mContext, "请稍等", "...Loading...");
			//sdcard/DCIM/Camera/2014_02_01_10_12_39.jpg/2014_02_01_10_12_39.jpg
			String fileName = getLastString(filepath);
			String extName=getExtString(fileName);
			String extName2=getExtString(newName);
			if(newName.trim().length()>0 && extName2==null){
				newName+=extName;
			}
			final String uploadFileName=newName;
			Log.i(TAG, "照片文件是否存在："+uploadFileName);
			new Thread(){
				public void run() {
					String URL = Network.API_DOMAIN+"/da";
					try {
						Log.d(TAG, "filepath:"+filepath);
						String ret=post(filepath,URL,uploadFileName);
						if(ret.equals(413)){
							fileMessageHandler.sendEmptyMessage(FILE_TO_LARGE);
						}else{
							fileMessageHandler.sendEmptyMessage(1);
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						fileMessageHandler.sendEmptyMessage(1);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						fileMessageHandler.sendEmptyMessage(1);
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						fileMessageHandler.sendEmptyMessage(1);
						e.printStackTrace();
					}
				};
			}.start();
		}
	}

	public String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException, JSONException {
		return post(pathToOurFile,urlServer,null);
	}
	public String post(String pathToOurFile,String urlServer,String fileName) throws ClientProtocolException, IOException, JSONException {
		HttpClient httpclient = new DefaultHttpClient();
		//设置通信协议版本
		httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

		//File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径

		//String pathToOurFile = path.getPath()+File.separator+"ak.txt"; //uploadfile
		//String urlServer = "http://192.168.1.88/test/upload.php"; 


		//		Map<String, String> params = new HashMap<String, String>();
		//		params.put("strParamName", "strParamValue");
		//		Map<String, File> files = new HashMap<String, File>();
		//		File file = new File(pathToOurFile);
		//		files.put("tempAndroid.txt", file);
		//		postnew(pathToOurFile, params, files);
		//		

		HttpPost httppost = new HttpPost(urlServer);
		File file = new File(pathToOurFile);
		Log.i(TAG, "上传文件大小："+file.length());
		MultipartEntity mpEntity = new MultipartEntity(); //文件传输
		FileBody cbFile=null;
		if(fileName==null || fileName.trim().length()==0){
			cbFile = new FileBody(file,"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword");
		}else{
			Log.i(TAG, "上传的文件名："+fileName);
			cbFile = new FileBody(file,fileName,"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword","UTF-8");
		}
		ContentBody client_id = new StringBody(mProjects.getClient_id());
		ContentBody details = new StringBody(xm_data_ed_con.getText().toString(), Charset.forName("UTF-8"));
		ContentBody project_id = new StringBody(mProjects.getProject_id());
		ContentBody token = new StringBody(tokens);
		ContentBody user_id = new StringBody(user_ids);
		ContentBody validation = new StringBody(CRMUserBaseInfo.kValication);
		//		mpEntity.addPart("data_files", cbFile); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("data_files", cbFile); 
		mpEntity.addPart("client_id", client_id); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("details", details); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("project_id", project_id); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("token", token); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("user_id", user_id); // <input type="file" name="userfile" />  对应的
		mpEntity.addPart("validation", validation); // <input type="file" name="userfile" />  对应的
		httppost.setEntity(mpEntity);

		Log.d(TAG,"executing request " + httppost.getRequestLine());
		HttpResponse response = httpclient.execute(httppost);
		//		response.getParams().setParameter("Charsert", "UTF-8");
		//		response.getParams().setParameter(, value)
		HttpEntity resEntity = response.getEntity();

		System.out.println(response.getStatusLine());//通信Ok
		Log.d(TAG,"getStatusLine " + response.getStatusLine());
		Log.d(TAG,"getStatusCode " + response.getStatusLine().getStatusCode());
		if(response.getStatusLine().getStatusCode()==413){
			return "413";
		}
		String json="";
		String path="";
		if (resEntity != null) {
			fileMessageHandler.sendEmptyMessage(1);
			json=EntityUtils.toString(resEntity,"utf-8");
			//			System.out.println(json);
			JSONObject p=null;
			try{
				p=new JSONObject(json);
				path=(String) p.get("path");
			}catch(Exception e){
				e.printStackTrace();
				//				fileMessageHandler.sendEmptyMessage(2);
			}
		}
		if (resEntity != null) {
			resEntity.consumeContent();
		}

		httpclient.getConnectionManager().shutdown();
		return path;
	}

	protected void doCropPhoto(Bitmap data){
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");
		intent.putExtra("data", data);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 128);
		intent.putExtra("outputY", 128);
		imageDir = "tempc.jpg";
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
				new File(Environment.getExternalStorageDirectory(), imageDir)));
		intent.putExtra("return-data", false);
		startActivityForResult(intent, TAKE_CORP);
	}


	// 图片缩放
	public void photoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, TAKE_CORP);
	}

	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//		image.compress(Bitmap.CompressFormat.JPEG, 70, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 30;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	private Bitmap getimagess(String srcPath) {
		System.out.println(" 1 bitmap   =  "+srcPath);
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
		return bitmap;//压缩好比例大小后再进行质量压缩
	}

	private void SavePicInLocal(Bitmap bitmap) {
		//		bitmap = getimagess(bitmap);
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		ByteArrayOutputStream baos = null; // 字节数组输出流
		try {
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.PNG, 30, baos);
			byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组
			imageDir = "temp1.jpg";
			File file = new File(Environment.getExternalStorageDirectory(), imageDir);
			// 将字节数组写入到刚创建的图片文件中
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(byteArray);

			Log.e("wop", "*** media filepath ***  === "+ file.getAbsolutePath());
			filepath = file.getAbsolutePath();
			fileMessageHandler.sendEmptyMessage(0);
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			if (requestCode == TAKE_PHOTO) {
				//				////				photoZoom(Uri.fromFile(picture));
				//								filepath = picture.getAbsolutePath();
				fileMessageHandler.sendEmptyMessage(3);
				//				Log.e("wop", "*** media filepath ***  === "+ picture.getAbsolutePath());
//				Bitmap photo = BitmapFactory.decodeFile(picture.getAbsolutePath());
			}
			//
			//			if (requestCode == TAKE_CORP) {
			//				if(intent!=null){
			//					Bundle bundle = intent.getExtras();
			//					if (bundle != null) {
			//						Bitmap photo = bundle.getParcelable("data");
			//						SavePicInLocal(photo);
			//					}
			//				}
			//			}

			if (requestCode == IMAGE_CODE) {
				if (intent == null)
					return;
				Uri originalUri = intent.getData(); // 获得图片的uri
				// content://media/external/images/media/141
				// file:///mnt/sdcard/Qhouse/MooMa3Gurl1365385868597.jpg
				String tmp = String.valueOf(originalUri);
				if(tmp.contains("sdcard")){
					int index = tmp.indexOf("sdcard");
					filepath = tmp.substring(index, tmp.length());
				}else if (tmp.contains("content://media/external/")) {
					String[] proj = { MediaColumns.DATA };
					Cursor cursor = managedQuery(originalUri, proj, null, null,
							null);
					if (cursor != null) {
						int column_index = cursor
						.getColumnIndexOrThrow(MediaColumns.DATA);
						cursor.moveToFirst();
						filepath = cursor.getString(column_index);
					}
				} else if (tmp.contains("file:///")) {
					filepath = tmp.substring(7, tmp.length());// /mnt/sdcard/Qhouse/MooMa3Gurl1365385868597.jpg
				}
				fileMessageHandler.sendEmptyMessage(0);
				Log.e("wop", "*** media filepath ***  === "+ filepath);
			}
			//			if (requestCode == PHOTO_RESULT) {
			//                Bundle extras = intent.getExtras();
			//                if (extras != null) {
			//                    Bitmap photo = extras.getParcelable("data");
			//                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
			//                    photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);
			//                    avatar.setImageBitmap(photo);
			//                }
			//            }
		}
	}

	private Handler fileMessageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (progressDialog!=null && progressDialog.isShowing()) {  
					progressDialog.dismiss();  
				}
				if(filepath.equals("")){
					openDailog("操作提示", "上传文件失败！");
				}else {
					DisplayMetrics dm = new DisplayMetrics();
					// 获取屏幕信息
					getWindowManager().getDefaultDisplay().getMetrics(dm);
					float screenScale = dm.scaledDensity;
					xm_data_iv.setImageBitmap(decodeSampledBitmapFromFile(filepath, (int)(LayoutParams.MATCH_PARENT-20*screenScale+1), (int)(LayoutParams.MATCH_PARENT-20*screenScale+1)));
				}
				break;
			case 1:
				if (progressDialog.isShowing()&&progressDialog!=null) {  
					progressDialog.dismiss();  
				}
				finish();
				break;
			case 2:
				Toast.makeText(mContext, "文件太大，请传小图.", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				filepath = Environment.getExternalStorageDirectory() + "/"+imageDir;
				Log.d(TAG, "imageDir:"+imageDir);
				fileMessageHandler.sendEmptyMessage(0);
//				progressDialog = ProgressDialog.show(mContext, "请稍等", "...图片加载中...");
//				File picture = new File(Environment.getExternalStorageDirectory() + "/" + imageDir);
//				Bitmap photo = getimagess(picture.getAbsolutePath());
//				if(photo!=null){
//					SavePicInLocal(photo);
//				}
				break;
			case FILE_TO_LARGE:
				openDailog2("网络信息","文件过大");
				break;
			}
		}
	};

	private void openDailog2(String title, String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定",null).show();
	}
	private String getLastString(String str) {  
		String[] splitStr = str.split("/");  
		int len = splitStr.length;  
		String result = splitStr[len-1];  
		return result;  
	}  

	private String getExtString(String str) {  
		int i=str.lastIndexOf('.');
		Log.d(TAG, "index:"+i);
		if(i>-1){
			return str.substring(str.lastIndexOf('.'));
		}else{
			return null;
		}
		
	}  
	public static Bitmap decodeSampledBitmapFromFile(String fileName ,  
			int reqWidth, int reqHeight) {  
		// First decode with inJustDecodeBounds=true to check dimensions  
		final BitmapFactory.Options options = new BitmapFactory.Options();  
		options.inJustDecodeBounds = true;  
		BitmapFactory.decodeFile(fileName, options); 
		// Calculate inSampleSize  
//		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
		options.inSampleSize = computeSampleSize(options, -1, 210*210);  

		options.inJustDecodeBounds = false;
		// Decode bitmap with inSampleSize set  
//		options.inJustDecodeBounds = false;  
		return BitmapFactory.decodeFile(fileName, options); 
	} 

	
	public static int computeSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,
	            maxNumOfPixels);
	    int roundedSize;
	    if (initialSize <= 8) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }
	    return roundedSize;
	}


	private static int computeInitialSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {

	    double w = options.outWidth;
	    double h = options.outHeight;
	    int lowerBound = (maxNumOfPixels == -1) ? 1 :
	            (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
	    int upperBound = (minSideLength == -1) ? 128 :
	            (int) Math.min(Math.floor(w / minSideLength),
	            Math.floor(h / minSideLength));
	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;
	    }
	    if ((maxNumOfPixels == -1) &&
	            (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	} 

	
	public static int calculateInSampleSize(  
			BitmapFactory.Options options, int reqWidth, int reqHeight) {  
		// Raw height and width of image  
		final int height = options.outHeight;  
		final int width = options.outWidth;  
		int inSampleSize = 1;  
		if (height > reqHeight || width > reqWidth) {  
			// Calculate ratios of height and width to requested height and width  
			final int heightRatio = Math.round((float) height / (float) reqHeight);  
			final int widthRatio = Math.round((float) width / (float) reqWidth);  
			// Choose the smallest ratio as inSampleSize value, this will guarantee  
			// a final image with both dimensions larger than or equal to the  
			// requested height and width.  
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;  
		}  
		return inSampleSize;  
	}  

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}